<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成名片</title>
    <link rel="stylesheet" href="./css/index.css" />
</head>
<body>
    <div class="box">
        <div id="container">
            <div class="container-border">
                   <img id="img" style="width: 200px;height: 200px;" src="img/t.png" />
                   <div class="detail">
                        <span class="nickname">张三</span>
                        <span class="job">WEB前端工程师</span>
                    </div>
                    <div class="introduce">3年ToB类产品开发经验，经常跨部门沟通，能够站在产品角度考虑问题。
                        较强的执行力，能推动和协同他人实现需求落地，并取得预期效果。
                        较强的产品思维，多次协助pm打造出优秀的项目。</div>
            </div>
        </div> 
        
        <div class="rightConent">
            <div>
                <input class="file-input" type="file" name="avatar" />
                <div class="file-font">上传头像</div>
            </div>
            
            <div class="inputBox">
                <input name="nickname" type="text" value="张三" placeholder="请输入昵称" required />
                <input name="job" type="text" value="WEB前端工程师" placeholder="请输入职位"required />
                <input name="introduce" type="text" value="3年ToB类产品开发经验，经常跨部门沟通，能够站在产品角度考虑问题。">
                <input name="picname" type="text" value="" placeholder="生成名片图片名称" />
            </div>
            
            <div id="save">保存图片</div>
        </div>
    </div>        

</body>
</html>
<script src="./js/jquery.min.js"></script>

<script src="./js/html2canvas.min.js"></script>

<script>
    $("input[name=nickname], input[name=job], input[name=introduce]").on('input', function(){
        var name = $(this).prop('name')
        var value = $.trim($(this).val())

        $(`.${name}`).text(value)

    })

    $("input[name=avatar]").change(function(){

        var file = this.files[0]

        var reader = new FileReader()

        reader.readAsDataURL(file)

        reader.onload = function()
        {
            if(this.result)
            {
                $("#img").attr("src", this.result)
            }
        }
    })

    $("#save").click(function(){
        var nickname = $.trim($("input[name=nickname]").val())
        var job = $.trim($('input[name=job]').val())
        var introduce = $.trim($('input[name=introduce]').val())

        if(!nickname)
        {
            alert("请输入姓名")
            $("input[name=nickname]").focus()
            return false
        }

        if (!job)
        {
            alert('请输入职位')
            $('input[name=job]').focus()
            return false
        }

        if (!introduce)
        {
            alert('请输入个人简介')
            $('input[name=introduce]').focus()
            return false
        }

        $('.nickname').text(nickname)
        $('.job').text(job)
        $('.introduce').text(introduce)

        let picname = $.trim($('input[name=picname]').val())
        picname = picname ? `${picname}.jpg` : "card.jpg"

        var container = document.getElementById("container")
        var width = container.offsetWidth
        var height = container.offsetHeight

        var canvas = document.createElement('canvas')
        var context = canvas.getContext('2d')

        var scale = GetPixelRatio(context);

        canvas.width = width * scale
        canvas.height = height * scale
        canvas.style.width = width + 'px'
        canvas.style.height = height + 'px'
        context.scale(scale, scale)

        let opts = {
            scale: scale,
            canvas: canvas,
            width: width,
            height: height,
            dpi:window.devicePixelRatio
        };

        html2canvas(container, opts).then(function(canvas){
            context.imageSmoothingEnabled = false;
            context.webkitImageSmoothingEnabled = false;
            context.msImageSmoothingEnabled = false;
            context.imageSmoothingEnabled = false;

            let dataUrl = canvas.toDataURL('image/jpeg', '1.0')

            DataURIToBlob(picname, dataUrl)
        })
    })

    let GetPixelRatio = function (content)
    {
        if(content)
        {
           let backingStore = content.backingStorePixelRatio ||
               content.webkitBackingStorePixelRatio ||
               content.mozBackingStorePixelRatio ||
               content.msBackingStorePixelRatio ||
               content.oBackingStorePixelRatio ||
               content.backingStorePixelRatio || 0.5;
            return (window.devicePixelRatio || 0.5) / backingStore;   
        }
    };

    let DataURIToBlob = function (picname, dataURI)
    {
        let binStr = atob(dataURI.split(',')[1]),
            len = binStr.length,
            arr = new Uint8Array(len);
        
        for (let i = 0; i < len; i++)
        {
            arr[i] = binStr.charCodeAt(i);
        } 
        
        var blob = new Blob([arr])

        var download = $("<a>")
            .attr("href", URL.createObjectURL(blob))
            .attr("download",picname)
            .appendTo("body")
            .on("click", function () {
                if (navigator.msSaveBlob)
                {
                    return navigator.msSaveBlob(blob, picname);
                }
            });
        download[0].click();
        download.remove();    
    }
</script>
